package me.wxk.interview.activemq.service;

import me.wxk.interview.activemq.constant.QueueName;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangxuekai
 * @version 2.3
 * @Date 2017/5/11.
 * @since 2.3
 */
public class RequestProcessor {
    private MessageConsumer consumer;
    private Session session;

    /**
     * ActiveMQObjectMessage
     * {commandId = 6, responseRequired = false, messageId = ID:HJS-PC0985HF-65415-1494488889423-1:1:1:1:1,
     * originalDestination = null, originalTransactionId = null, producerId = ID:HJS-PC0985HF-65415-1494488889423-1:1:1:1,
     * destination = queue://RequestQueue, transactionId = TX:ID:HJS-PC0985HF-65415-1494488889423-1:1:1, expiration = 0,
     * timestamp = 1494488889629, arrival = 0, brokerInTime = 1494488722642, brokerOutTime = 1494488722648, correlationId = null,
     * replyTo = null, persistent = false, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null,
     * compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@7f1228, marshalledProperties = null,
     * dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = true, readOnlyBody = true,
     * droppable = false}
     */

    public void requestHandler(HashMap<Serializable, Serializable> requestParam) {
        System.out.println("requestHandler----->" + requestParam);

        for (Map.Entry<Serializable, Serializable> entry : requestParam.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

    public void init() throws JMSException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://192.168.43.129:61616");

        Connection connection = connectionFactory.createConnection();
        connection.start();

        session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(QueueName.TEST);

        // 创建消费者
        consumer = session.createConsumer(destination);
    }

    public static void main(String[] args) throws JMSException {
        RequestProcessor processor = new RequestProcessor();
        processor.init();

        while (true) {
            ObjectMessage message = (ObjectMessage) processor.consumer.receive(1000);


            if (message == null) {
                System.out.println("null");
            } else {
                System.out.println(message);
                HashMap<Serializable, Serializable> requestParam = (HashMap<Serializable, Serializable>) message.getObject();
                processor.requestHandler(requestParam);
            }
        }
    }
}
